package org.dromara.common.json.fastjson.serilizer;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.IOException;
import java.lang.reflect.Type;

public class LongSerializer implements ObjectSerializer {

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;

        if (object == null) {
            out.writeNull(SerializerFeature.WriteNullNumberAsZero);
        } else {
            long value = ((Long) object).longValue();
            // 长度超过16位
            if (value >= 1000000000000000l) {
                out.write("\"");

                out.writeLong(value);

                if (out.isEnabled(SerializerFeature.WriteClassName) //
                        && value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE //
                        && fieldType != Long.class
                        && fieldType != long.class) {
                    out.write('L');
                }
                out.write("\"");
            } else {
                out.writeLong(value);
                if (out.isEnabled(SerializerFeature.WriteClassName) //
                        && value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE //
                        && fieldType != Long.class
                        && fieldType != long.class) {
                    out.write('L');
                }
            }

        }
    }
}
